/*
  学习目标：受控组件改造 -收集用户输入内容, 回填表单数据 - 


*/

import React from 'react';
import './index.css';

export default class App extends React.Component {
  state = {
    // 用户名输入框
    username: '',
    // 评论内容
    content: '',
    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  handleDelById = (id) => {
    const list = this.state.list.filter((item) => item.id !== id);
    this.setState({ list });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  // 3. 定义新增的事件函数
  handleAdd = (e) => {
    // 5. 阻止默认行为
    e.preventDefault();
    const { username, content, list } = this.state;
    // 6. 通过setState修改list
    const newItem = { username, content, id: Date.now() };
    // 7. 通过受控组件, 清空表单的值
    this.setState({ list: [newItem, ...list], username: '', content: '' });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form>
          <input
            // 1. state控制value
            value={username}
            // 2. onChange配合setState修改数据
            onChange={this.handleChange}
            name="username"
            className="user"
            type="text"
            placeholder="请输入评论人"
          />
          <br />
          <textarea
            value={content}
            // 2. onChange配合setState修改数据
            onChange={this.handleChange}
            name="content"
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button
            // 4. 点击事件绑定新增
            onClick={this.handleAdd}
          >
            发表评论
          </button>
          <button type="button" onClick={this.handleClear}>
            清空评论
          </button>
        </form>
        {list.length ? (
          <ul>
            {list.map((item) => (
              <li key={item.id}>
                <h3>评论人: {item.username}</h3>
                <p>评论内容：{item.content}</p>
                <button onClick={() => this.handleDelById(item.id)}>删除</button>
              </li>
            ))}
          </ul>
        ) : (
          <div>暂无数据</div>
        )}
      </div>
    );
  }
}
